package model

import "gorm.io/gorm"

type User struct {
	Model
	Username   string     `json:"username,omitempty"`
	Nickname   string     `json:"nickname,omitempty"`
	Password   string     `json:"password,omitempty"`
	Categories []Category `json:"categories,omitempty" gorm:"foreignKey:UserID"`
	Pictures   []Picture  `json:"details,omitempty" gorm:"foreignKey:UserID"`
}

func (u User) TableName() string {
	return "img_user"
}

func (u User) Create(db *gorm.DB) error {
	return db.Transaction(func(tx *gorm.DB) error {
		// 在事务中执行一些 db 操作（从这里开始，您应该使用 'tx' 而不是 'db'）
		if err := tx.Create(&u).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		commonCategory := Category{
			Name:   "我的图片",
			Desc:   "默认收藏夹",
			UserID: u.ID,
			Type:   1,
		}
		if err := tx.Create(&commonCategory).Error; err != nil {
			return err
		}

		// 返回 nil 提交事务
		return nil
	})
}

func (u User) GetByUsername(db *gorm.DB) (*User, error) {
	var user User
	err := db.Where("username = ?", u.Username).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}
func (u User) GetByID(db *gorm.DB) (*User, error) {
	var user User
	err := db.Where("id = ?", u.ID).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}
func (u User) ListInID(db *gorm.DB, ids [][]interface{}, pageOffset int, pageSize int) ([]*User, error) {
	var users []*User
	err := db.Where("(id) IN ?", ids).Find(&users).Error
	return users, err
}

func (u User) CheckByUsernameAndPassword(db *gorm.DB) (*User, error) {
	var user User
	err := db.Where("username = ? && password = ?", u.Username, u.Password).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}
